package com.weng.coder.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.weng.cloud.utils.CloudAuthUtil;
import com.weng.coder.common.utils.FileUtil;
import com.weng.coder.entity.CodeTable;
import com.weng.framework.core.model.ResponseData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.weng.coder.service.CodeService;
import com.weng.coder.service.CodeTableService;
import com.weng.coder.service.TemplateService;
import com.weng.coder.common.CommonProperties;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 生成代码 Web API
 *
 * @作者 wengzhonghui
 * @创建时间 2018-02-25 15:49:52
 */
@RestController
@RequestMapping("/generate-code") 
@Api(value = "生成代码相关接口")
public class GenerateCodeController{
	@Resource
	private TemplateService templateService;
	@Resource
	private CodeService codeService;
	@Resource
	private CodeTableService codeTableService;
    
	
	 /**
     * 生成代码
     * 
     * @author wengzhonghui 2017年7月12日
     * @param templateIds
     * @param tableIds
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/templates-tables",method=RequestMethod.POST)
    @ApiOperation(value = "生成代码", notes = "templateIds多个以,号分隔;tableIds多个以,号他隔")
    public ResponseData generatedCodeByTemplatesAndTables(String templateIds, String tableIds
    		, String isCatalog, HttpServletRequest request) {
    	if(StringUtils.isEmpty(templateIds) || StringUtils.isEmpty(tableIds)){
    		return ResponseData.failed("请选择模板和表格");
    	}
			String userName = CloudAuthUtil.getCurUserId(request);

    	String[] templateIdList = templateIds.split(",");
    	String[] tableIdList = tableIds.split(",");
    	Map<String,Object> generateInfos = this.codeService.generateCodeFile( templateIdList, tableIdList
    			, CommonProperties.generateExcelPath, isCatalog,userName);
    	String downLoadPath = generateInfos.get("path").toString();
    	downLoadPath = CommonProperties.downloadExcelPath + "/"+ downLoadPath;
    	generateInfos.put("path", downLoadPath);
    	return ResponseData.success(generateInfos);
    }
    
    /**
     * 生成一个表所有模板的代码
     * 
     * @author wengzhonghui 2017年7月12日
     * @return
     * @throws IOException 
     */
    @ResponseBody
    @RequestMapping(value="/one-table",method=RequestMethod.GET)
    @ApiOperation(value = "生成一个表所有模板的代码", notes = "tableId:表格ID")
    public ResponseData generatedCodeByOneTables(  String tableId,String isCatalog,HttpServletRequest request
    		, HttpServletResponse response) throws IOException {
    	if(StringUtils.isEmpty(tableId) ){
    		return ResponseData.failed("请选择一个表格!");
    	}
    	CodeTable codeTable = this.codeTableService.getOne(tableId);
    	if(codeTable==null){
    		return ResponseData.failed("需要生成代码的表格不存在!");
    	}
    	List<String> templateIdList = this.templateService.getTemplateIdsByProjectId(codeTable.getProjectId());
    	if(templateIdList==null || templateIdList.size()==0){
    		return ResponseData.failed("尚未添加模板，请先添加模板!");
    	}
    	isCatalog = isCatalog==null?"0":isCatalog;
    	String userName = CloudAuthUtil.getCurUserTrueName(request);

    	String[] tableIdList = {tableId};
    	Map<String,Object> generateInfos = this.codeService.generateCodeFile( (String[])templateIdList.toArray(new String[0]), tableIdList
    			, CommonProperties.generateExcelPath, isCatalog,userName);
    	String downLoadPath = generateInfos.get("path").toString();
    	downLoadPath = CommonProperties.downloadExcelPath + "/"+ downLoadPath;
    	generateInfos.put("path", downLoadPath);
    	File tarZip = (File)generateInfos.get("tarZip");
    	return ResponseData.success(tarZip.getAbsolutePath());
    }
    
    
    /**
     * 生成一个表所有模板的代码
     * 
     * @author wengzhonghui 2017年7月12日
     * @return
     * @throws IOException 
     */
    @ResponseBody
    @RequestMapping(value="/preview",method=RequestMethod.GET)
    @ApiOperation(value = "获取一个表一个模板的代码", notes = "tableId:表格ID;templateId:模板ID")
    public ResponseData preview(  String tableId,String templateId,HttpServletRequest request
    		, HttpServletResponse response) throws IOException {
    	if(StringUtils.isEmpty(tableId) ){
    		return ResponseData.failed("请选择一个表格!");
    	}
//    	CodeTable codeTable = this.codeTableService.getOne(tableId);
//    	if(codeTable==null){
//    		return ResponseData.getFailResponseByMessage("需要生成代码的表格不存在!");
//    	}
    	String userName = CloudAuthUtil.getCurUserTrueName(request);

    	String content = this.codeService.generateCodeFileByTemplateAndTableId(tableId, templateId, userName);
    	return ResponseData.success(content);
    }
    
    @ResponseBody
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void download(String filePath, HttpServletResponse response) throws UnsupportedEncodingException, IOException {
        if(StringUtils.isEmpty(filePath)){
        	return;
        }
    	File file = new File(filePath);
    	if(!file.exists()){
    		return;
    	}
    	byte[] data = FileUtil.fileToBytes(file);
        response.setContentType("application/x-msdownload; charset=UTF-8");
        response.setContentLength(data.length);
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(data);
        outputStream.flush();
        outputStream.close();
    }
}

